# handle_post_location.py - Handle queue requests to post a location change.
# Copyright 2010 Nick renny <nickrenny@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import logging
import yaml
import traceback
import twitter
import tweet

import wsgiref.handlers
from google.appengine.runtime import DeadlineExceededError
from google.appengine.ext import webapp

class LocationWorker(webapp.RequestHandler):
    def post(self):
        dgr_yaml_path = self.request.get('dgr-yaml-path')
        twitter_username = self.request.get('twitter-username')
        twitter_password = self.request.get('twitter-password')
        tweet_id = self.request.get('tweet-id')
        tweet_user = self.request.get('tweet-user')
        tweet_url = self.request.get('tweet-url')
        tweet_message = self.request.get('tweet-message')
        if(dgr_yaml_path):
            try:
                tweet.connect_to_twitter(twitter_username, twitter_password)
                #message = tweet.Tweet(tweet_user, tweet_message, tweet_url, 
                #                      tweet_id, random.randint(0, 1))
                #tweet.tweet(message.to_retweet())
                tweet.newstyle_retweet(tweet_id)
            except DeadlineExceededError, exc:
                # Re-throw the exception, returning an HTTP 500 result
                # This will result in this task being called again soon
                raise exc
            except Exception, e:
                logging.error(type(e))
                logging.error(e)
                logging.error(traceback.format_exc())
                # Re-throw the exception so we get called again soon
                raise e

def main():
    wsgiref.handlers.CGIHandler().run(webapp.WSGIApplication([
                ('/post-location', LocationWorker)], debug=True))
    
if __name__ == '__main__':
    logging.getLogger().setLevel(logging.DEBUG)
    main()
